package Servlet.admin;

import domain.SysUser;
import service.AdminService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/userManagement")
public class UserManagementServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Long reqAdminPageIndex = 1L;
        Long pageSize = 4L;
        String value=request.getParameter("search");
        String reqUserPageIndex=request.getParameter("reqUserPageIndex");

        if (reqUserPageIndex != null){
            reqAdminPageIndex = Long.parseLong(reqUserPageIndex);
        }

        Long adminIndex = (reqAdminPageIndex - 1) * pageSize;

        List<SysUser> userDataList = AdminService.getUserData(adminIndex, pageSize);
        int total = AdminService.getUserTotal();
//        System.out.println(total);
        Long pageCount = total / pageSize;

        if (total % pageSize != 0) pageCount++;

        request.setAttribute("userDataList", userDataList);
        request.setAttribute("total", total);
        request.setAttribute("pageCount", pageCount);
        request.setAttribute("reqUserPageIndex", reqUserPageIndex);

        if (value != null){
            userDataList = AdminService.getUserContentByKeyWord(value);
            request.setAttribute("userDataList", userDataList);
            request.setAttribute("total", "");
            request.setAttribute("pageCount", "");
            request.setAttribute("reqAdminPageIndex", "");
        }

        request.getRequestDispatcher("/admin/userManagement.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
